package com.yyfax.ph.progress.search;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.yyfax.common.form.SearchBar;
import com.yyfax.common.form.interaction.SearchBarInteraction;
import com.yyfax.common.recycler.StatesAdapter;
import com.yyfax.common.recyclerview.IRecyclerView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.RecyclerListFragment;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.utils.Constants;
import com.yyfax.ph.progress.detail.ProgressDetailActivity;

import java.util.List;

/**
 * 产品页
 * Created by ying_he on 2017/10/27.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class ProgressFragment extends RecyclerListFragment implements ProgressPresenter.View, StatusAdapter.StatusItemClickListener,
		PopupWindow.OnDismissListener, StatesAdapter.RetryClickListener, SearchBarInteraction.SearchContentListener,
		SearchBarInteraction.SearchBarOnClickListener, View.OnClickListener {

	private static final int LOADER_ID = 100005;
	public static final int FIRST_PAGE = 1;

	@BindView(R.id.search_bar)
	SearchBar mSearchBar;
	@BindView(R.id.loan_user_tv)
	TextView mLoanUserTv;
	@BindView(R.id.status_btn)
	TextView mStatusBtn;
	@BindView(R.id.head_view)
	View mHeadView;
	@BindView(R.id.progress_lv)
	IRecyclerView mProgressLv;
	@BindView(R.id.pop_window_mask_status)
	View mPopWindowMaskStatus;
	@BindView(R.id.pop_window_mask)
	View mPopWindowMask;


	private int mPageNum = 1;
	private int mPageSize = 20;
	private int mStatusPosition;
	private String mSearchContent;

	private PopupWindow mPopupWindow;
	private StatusAdapter mPopupListAdapter;

	private ProgressAdapter mProgressAdapter;
	private ProgressPresenter mProgressPresenter;
	private Unbinder mBind;

	/**
	 * 是否需要刷新，进度详情回退不需要刷新，从其他地方跳转过来的需要刷新
	 */
	private boolean mNeedRefresh = true;

	public static ProgressFragment newInstance() {
		return new ProgressFragment();
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.progress_fragment, null);
		mBind = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		mSearchBar.setShadow(mPopWindowMask);
		mSearchBar.setSearchBarOnClickListener(this);
		mSearchBar.setSearchContentListener(this);
		mPopWindowMaskStatus.setOnClickListener(this);
		mStatusBtn.setOnClickListener(this);
		View statusContentView = View.inflate(getContext(), R.layout.select_status_layout, null);
		mPopupListAdapter = new StatusAdapter(this);
		((ListView) statusContentView.findViewById(R.id.select_status_lv)).setAdapter(mPopupListAdapter);
		mPopupWindow = new PopupWindow(statusContentView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);
		mPopupWindow.setOutsideTouchable(false);
		mPopupWindow.setOnDismissListener(this);
		mProgressAdapter = new ProgressAdapter(this);
		setup(this, R.id.progress_lv, 1, mProgressAdapter);
		mProgressLv.setRefreshHeaderBgColor(getResources().getColor(R.color.color_white));
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID, null, this);
	}

	public void setNeedRefresh(boolean refresh) {
		mNeedRefresh = refresh;
	}

	public void initData() {
		if (mProgressPresenter != null && mProgressAdapter != null && mNeedRefresh) {
			mSearchBar.returnNormalStatus();
			setNormalStatus();
			onRefresh();
		}
	}

	private void setNormalStatus() {
		mSearchContent = "";
		mStatusPosition = 0;
		String status = mPopupListAdapter.getStatus().get(mStatusPosition);
		mStatusBtn.setText(status);
		mPopupListAdapter.setSelectedStatus(status);

	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID);
		mProgressPresenter = null;
		mBind.unbind();
	}

	public void dismissPopupWindow() {
		if (null != mPopupWindow) {
			mPopupWindow.dismiss();
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(getActivity(), new ProgressPresenter.Generator());
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		if (null == mProgressPresenter) {
			mProgressPresenter = (ProgressPresenter) data;
			mProgressPresenter.attach(this);
			setNormalStatus();
			onRefresh();
		}
	}

	private void requestData(boolean isRefresh) {
		mPageNum = isRefresh ? FIRST_PAGE : ++mPageNum;
		String status = Constants.PROGRESS_STATUS_ALL;
		switch (mStatusPosition) {
			case 1:
				status = Constants.PROGRESS_STATUS_WAITE_DEAL;
				break;
			case 2:
				status = Constants.PROGRESS_STATUS_APPROVAL;
				break;
			case 3:
				status = Constants.PROGRESS_STATUS_CONTRACT;
				break;
			case 4:
				status = Constants.PROGRESS_STATUS_REJECT;
				break;
		}
		mProgressPresenter.getProgress(mSearchContent, status, mPageNum, mPageSize);
	}

	@Override
	public void searchContent(int searchType, String content) {
		mSearchContent = content;
		onRefresh();
	}

	@Override
	public void onRefresh() {
		StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_D001);
		requestData(true);
	}

	@Override
	public void onLoadMore() {
		//如果当前页有20条数据，则从后台加载数据
		if ((mProgressAdapter.getCount() % mPageSize) == 0) {
			requestData(false);
		} else {
			mRecyclerView.stopLoading();
		}
	}

	@Override
	public void onRetry() {
		mRecyclerView.setRefreshing(true);
	}

	@Override
	public void refreshSuccess(List<ProgressModel.ProgressBean> list) {
		if (list != null && list.size() == mPageSize){
			mRecyclerView.setLoadMoreEnabled(true);
		}else {
			mRecyclerView.setLoadMoreEnabled(false);
		}
		mRecyclerView.stopRefresh();
		mStatesAdapter.refreshData(list);
	}

	@Override
	public void loadMoreSuccess(List<ProgressModel.ProgressBean> list) {
		mRecyclerView.stopLoading();
		mStatesAdapter.loadData(list);
	}

	@Override
	public void onGetProgressFailure(String tips) {
		mPageNum--;
		mRecyclerView.setRefreshing(false);
		mRecyclerView.stopLoading();
		if (mPageNum <= 1) {
			mStatesAdapter.setState(com.yyfax.common.adapter.StatesAdapter.STATE_ERROR);
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		dismissPopupWindow();
	}

	/**
	 * 选择状态click事件
	 */
	@Override
	public void onStatusItemClick(int position, String selectStatus) {
		dismissPopupWindow();
		mStatusPosition = position;
		mStatusBtn.setText(mPopupListAdapter.getStatus().get(position));
		mPopupListAdapter.setSelectedStatus(mPopupListAdapter.getStatus().get(position));
		onRefresh();
	}

	@Override
	public void onDismiss() {
		mPopWindowMaskStatus.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View view) {
		if (view.getId() == R.id.status_btn && !mPopupWindow.isShowing()) {
			mPopupWindow.showAsDropDown(mHeadView, 0, 0);
			mPopWindowMaskStatus.setVisibility(View.VISIBLE);
		} else {
			dismissPopupWindow();
			if(view.getId() != R.id.pop_window_mask_status && view.getId() != R.id.pop_window_mask){
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_D002);
			}
		}
	}

	@Override
	public void onItemClick(int position, Object o, View v) {
		ProgressModel.ProgressBean bean = (ProgressModel.ProgressBean) o;
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_D003, bean.status);
		mNeedRefresh = false;
		ProgressDetailActivity.start(getActivity(), bean.taskNo);
	}

}
